﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace Attendance
{
    public partial class frmMain : Form
    {
        private string teacherID;//教师工号
        private string classTime;
        internal string TeacherID { get{return teacherID;} }//只读教师工号属性
        internal DataSet Teacher { get; set; }//教师信息数据集
        internal DataSet Subject { get; set; }//课程信息数据集
        internal string CronID { get; set; }
        internal string ClassTime { get { return classTime; } }
        HttpServer http = new HttpServer();//通讯类
        DataSet dsStudent = new DataSet();
        BindingSource bsStudent = new BindingSource();//学生信息数据绑定
        //public static SerialPort serialPort1;
        CardPort cp = new CardPort();//读卡器操作
        DataSet dsChkedStu = new DataSet();//已签到学生
        BindingSource bsChkedStu = new BindingSource();//已签到学生
        
        private HttpServer httpServer = new HttpServer();

        public delegate void CardMacReceived();

        void serial_port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            // 更新主线程上的控件来显示数据
            //Dispatcher.Invoke(new DelegateUpdateUI(this.UpdateControl));
            this.Invoke(new CardMacReceived(MessageCard));
            // throw new NotImplementedException();
        }

        void MessageCard()
        {
            MessageBox.Show(cp.CardMac);
        }

        public frmMain()
        {
            InitializeComponent();
        }
        DateTime time = new DateTime(2014,08,01,07,30,00);
        

        private void frmMain_Load(object sender, EventArgs e)
        {
            //CardMacReceived(serial_port_DataReceived);
            //test abort login start
            Teacher = new DataSet();
            Subject = new DataSet();
            httpServer.chkLogin("test", "test123456", Teacher, Subject);
            //test abort login end

            teacherID = Teacher.Tables["teacher"].Rows[0][0].ToString();    //读取教师工号
            label1.Text = Teacher.Tables["teacher"].Rows[0][1].ToString();
            BindngSubject();//课程信息添加
            btnStop.Visible = false;

            //StreamReader sr = new StreamReader(http.GetSubject(TeacherID).ToString());

            ////DataSet dsSubject = new DataSet();  //Dataset for subject
            ////dsSubject.ReadXml(http.GetSubject(TeacherID));
            ////cboSubject.DataSource = dsSubject.Tables["SubjectInfo"];
            ////cboSubject.ValueMember = dsSubject.Tables[0].Columns[0].ToString();
            ////cboSubject.DisplayMember = dsSubject.Tables[0].Columns[1].ToString();
            //label2.Text = time.ToLongTimeString();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void BindngSubject()//绑定课程
        {
            /*课程下拉菜单数据源*/
            BindingSource bsSubject = new BindingSource();
            bsSubject.DataSource = Subject.Tables["subject"];
            cboSubject.ValueMember = "subjectNumber";
            cboSubject.DisplayMember = "name";
            cboSubject.DataSource = bsSubject;
        }

        private void cboSubject_SelectedIndexChanged(object sender, EventArgs e)//选择课程获取班级
        {
            string subjectID = cboSubject.SelectedValue.ToString();
            DataSet dsSession = new DataSet();
            http.GetSession(teacherID, subjectID, dsSession);
            /*班级下拉菜单数据源*/
            cboClass.DisplayMember = "className";
            cboClass.ValueMember = "sessionNumber";
            cboClass.DataSource = dsSession.Tables["Session"];
        }

        private void cboClass_SelectedIndexChanged(object sender, EventArgs e)//选择班级获取计划
        {
            string session = cboClass.SelectedValue.ToString();
            //MessageBox.Show(session);
            DataSet dsCron = new DataSet();
            DataSet dsLesson = new DataSet();
            try
            {
                http.GetCron(TeacherID, session, dsCron, dsLesson, dsStudent);
                bsStudent.DataSource = dsStudent.Tables["student"];
                /*计划下拉菜单数据源*/
                cboCron.DisplayMember = "executeDate";
                cboCron.ValueMember = "cronNumber";
                cboCron.DataSource = dsCron.Tables["Cron"];
                dgvStudent.DataSource = bsStudent;
                bsStudent.Sort = "studentNumber";
                this.classTime = dsLesson.Tables["lesson"].Rows[0]["startTime"].ToString();
                //软件服务器时间校准
                Regex reDate = new Regex("-");
                string[] arrayDate = reDate.Split(dsCron.Tables["Cron"].Rows[0]["executeDate"].ToString());
                Regex reTime = new Regex(":");
                string[] arrayTime = reTime.Split(dsCron.Tables["Cron"].Rows[0]["executeTime"].ToString());
                time = new DateTime(Convert.ToInt32(arrayDate[0]), Convert.ToInt32(arrayDate[1]), Convert.ToInt32(arrayDate[2]), Convert.ToInt32(arrayTime[0]), Convert.ToInt32(arrayTime[1]), Convert.ToInt32(arrayTime[2]));
                CronID = dsCron.Tables["Cron"].Rows[0]["cronNumber"].ToString();
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void cboCron_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



        /*
         * 刷卡部分
         * 
         * 
         * 
         */



        //private void button1_Click(object sender, EventArgs e)
        //{
        //    //dsStudent.Tables[0].s
        //    int index = bsStudent.Find("cardmac", txtTestID.Text);
        //    //bindingSource.Position = bindingSource.Find("ID",txtTestID.Text);
        //    dgvStudent.Rows[index].Cells[2].Style.BackColor = Color.Green;
        //    //dsStudent.Tables[0].Rows[index][2] = "ok";
        //}

        private void timerTime_Tick(object sender, EventArgs e)//软件程序时间
        {
            time = time.AddSeconds(1);
            label2.Text = time.ToLongTimeString();
        }

        private void btnStop_Click(object sender, EventArgs e)//结束考勤
        {
            //bgwGetCard.CancelAsync();
            cp.serialPort.DataReceived -= new SerialDataReceivedEventHandler(ReadPort);
            cp.ClosePorts();
            DataTable dt = dsStudent.Tables["student"];
            DataTable dtAdd = dsChkedStu.Tables["ChkedStu"];
            foreach (DataRow dr in dt.Rows)
            {
                DataRow drAdd = dtAdd.NewRow();
                drAdd["stuid"] = dr["studentNumber"].ToString();
                drAdd["name"] = dr["name"].ToString();
                drAdd["mac"] = dr["cardMac"].ToString();
                drAdd["absent"] = "未考勤";
                drAdd["date"] = time.Date.ToString("yyyy-MM-dd");
                drAdd["time"] = time.TimeOfDay;
                dtAdd.Rows.Add(drAdd);

                //MessageBox.Show(dr["stuid"].ToString());
                //bsStudent.RemoveAt(0);
                //dt.Rows.Remove(dr);
            }
            http.Upload(TeacherID, CronID, time.TimeOfDay.ToString(), dsChkedStu.Tables[0]);
            dt.Clear();

            btnStart.Visible = true;
            btnStop.Visible = false;
        }

        private void btnStart_Click(object sender, EventArgs e)//开始考勤
        {
            try
            {
                cp.ChkPorts();
                cp.OpenPorts();
                //cp.serialPort.DataReceived += new SerialDataReceivedEventHandler(ReadPort);
                //bgwGetCard.RunWorkerAsync();
                cp.DataReceived(serial_port_DataReceived);
                InitialSet();
                btnStart.Visible = false;
                btnStop.Visible = true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void InitialSet()
        {
            dsChkedStu.Reset();
            DataTable tb = dsChkedStu.Tables.Add("ChkedStu");
            tb.Columns.Add("stuID", typeof(string));//学号
            tb.Columns.Add("name", typeof(string));//学号
            tb.Columns.Add("mac", typeof(string));//物理卡号
            tb.Columns.Add("absent", typeof(string));//考勤情况
            tb.Columns.Add("date", typeof(string));//考勤日期
            tb.Columns.Add("time", typeof(string));//考勤时间
            bsChkedStu.DataSource = dsChkedStu.Tables["ChkedStu"];
            dgvChkedStu.DataSource = bsChkedStu;
        }

        public void ReadPort(Object sender, SerialDataReceivedEventArgs e)//卡号获取托管
        {
            GetCardMac();
        }

        private static string ByteArrayToHexString(byte[] data)//二进制转十六进制
        {
            StringBuilder sb = new StringBuilder(data.Length * 3);
            foreach (byte b in data)
                sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            string a = sb.ToString();
            return sb.ToString().ToUpper();
        }

        private void GetCardMac()//获取卡号函数
        {
            //获取物理卡号过程
            string s100 = "";
            Thread.Sleep(100);
            byte[] readBuffer = new byte[4];
            cp.serialPort.Read(readBuffer, 0, 4);
            s100 = ByteArrayToHexString(readBuffer);
            s100 = s100.Replace(" ", "");

            //十六进制的物理卡号转成十进制
            s100 = Convert.ToInt64(s100, 16).ToString();
            cp.CardMac = s100;
            //throw new Exception(CardMac);
            //MessageBox.Show(cp.CardMac);
            CardChked(cp.CardMac);
            //MessageBox.Show(s100);
        }

        delegate void dgvFlush(DataGridView dgv);
        void DataFlush(DataGridView dgv)
        {
            dgv.Refresh();
        }

        private void CardChked(string mac)
        {
            try
            {
                int index = bsStudent.Find("cardmac", mac);
                DataTable dt = dsChkedStu.Tables["ChkedStu"];
                DataRow dr = dt.NewRow();
                dr["stuid"] = dgvStudent.Rows[index].Cells["studentNumber"].Value.ToString();
                dr["name"] = dgvStudent.Rows[index].Cells["name"].Value.ToString();
                dr["mac"] = dgvStudent.Rows[index].Cells["cardMac"].Value.ToString();
                dr["absent"] = "正常考勤";
                dr["date"] = time.Date.ToString("yyyy-MM-dd");
                dr["time"] = time.TimeOfDay;
                dt.Rows.Add(dr);
                //MessageBox.Show(dr["stuid"].ToString());
                bsStudent.RemoveAt(index);
                //dgvStudent.Refresh();
                dgvStudent.Invoke(new dgvFlush(DataFlush), dgvStudent);
                dgvChkedStu.Invoke(new dgvFlush(DataFlush), dgvChkedStu);
                pictureBox1.ImageLocation = @"http://signals.hyit.edu.cn:8080/attendanceV3/photo/" + dr["stuid"] + ".png";
            }
            catch (ArgumentOutOfRangeException ex)
            {
                try
                {
                    int index = bsChkedStu.Find("mac", mac);
                    dgvChkedStu.Rows[index].Cells["stuid"].Value.ToString();
                    MessageBox.Show("已签到！");
                }
                catch (ArgumentOutOfRangeException)
                {
                    MessageBox.Show("不存在的卡！");
                }
            }

        }

        //private void bgwGetCard_DoWork(object sender, DoWorkEventArgs e)
        //{
        //    BackgroundWorker worker = (BackgroundWorker)sender;
        //    e.Result = GetCardMac(worker, e);
        //}

        //private bool GetCardMac(BackgroundWorker worker, DoWorkEventArgs e)
        //{
        //    while (true)
        //    {
        //        if (worker.CancellationPending == true)
        //        {
        //            e.Cancel = true;
        //            break;
        //        }
        //        else
        //        {
        //            if (cp.CardMac != "")
        //            {
        //                try
        //                {
        //                    string mac = cp.CardMac;
        //                    CardChked(mac);
        //                    //MessageBox.Show(cp.CardMac);
        //                    //bindingSource.Position = bindingSource.Find("ID",txtTestID.Text);
        //                    //dgStudent.Rows[index].Cells[2].Style.BackColor = Color.Green;
                            
        //                }
        //                catch (ArgumentOutOfRangeException ex)
        //                {
        //                    MessageBox.Show("不存在的卡！");
        //                }
        //                finally
        //                {
        //                    cp.CardMac = "";
        //                    Thread.Sleep(100);
        //                }
        //            }
        //        }
        //    }
        //    return true;
        //}

        //private void bgwGetCard_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        //{
        //    if (e.Error != null)
        //    {
        //        MessageBox.Show(e.Error.Message);
        //    }
        //    else if (e.Cancelled == true)
        //    {
        //        cp.ClosePorts();
        //        cp.serialPort.Close();
        //    }
        //    else
        //    {
        //        cp.ClosePorts();
        //    }

        //}

    }
}
